/**
 * ajax 服务路由集合
 */
const router = require('koa-router')({
    prefix: '/weapp'
})

const controllers = require('../controllers')
const multer = require('koa-multer')
const path = require('path')
const fs = require('fs')

global.fileNum = 0
const storage = multer.diskStorage({
    //文件保存路径
    destination: function(req, file, cb) {
        const dir = path.join(__dirname, `../public/${req.body.folder}`)
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
        cb(null, dir)
    },
    //修改文件名称
    filename: function(req, file, cb) {
    	const filename = `${Date.now()}${Math.ceil(Math.random() * Math.random() * 111)}.${file.originalname.split(".").pop()}`
        if (req.body.folder == 'musics') {
            req.body.source = `${req.body.folder}/${filename}`
        } else if (!req.body.card) {
            req.body[file.fieldname] = `${req.body.folder}/${filename}`
        } else {
            if (!req.body['files']) {
                req.body['files'] = {}
            }
            req.body['files'][req.body.fileIndex.split(',')[global.fileNum]] = filename
            global.fileNum++
        }
        cb(null, filename)
    }
})

const upload = multer({ storage: storage })

const cardFiles = [{
    name: 'float_url',
    maxCount: 1
}, {
    name: 'display_url',
    maxCount: 1
}, {
    name: 'swiper_url',
    maxCount: 1
}, {
    name: 'share_url',
    maxCount: 1
}]

// --- 贺卡index页面数据 --- //
router.post('/index_data', controllers.index_data)

// --- 贺卡kind页面数据 --- //
router.post('/kind_data', controllers.kind_data)

// --- 贺卡card页面数据 --- //
router.post('/card_data', controllers.card_data)

// --- 登录接口 --- //
router.post('/login', controllers.login)

// --- 贺卡管理接口 --- //
router.post('/card', upload.fields(cardFiles), controllers.card)

// --- 修改密码接口 --- //
router.post('/resetPass', controllers.resetPass)

// --- 修改贺卡类型接口 --- //
router.post('/kind', controllers.kind)

// --- 修改祝福语接口 --- //
router.post('/wish', controllers.wish)

// --- 修改音乐接口 --- //
router.post('/music', upload.single('source'), controllers.music)

// --- 修改图片接口 --- //
router.post('/image', upload.array('source', 50), controllers.image)

module.exports = router